import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    theme: localStorage.getItem('theme') || 'system',
    language: localStorage.getItem('language') || 'zh'
  },
  mutations: {
    setTheme(state, theme) {
      const actualTheme = theme === 'system' 
        ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
        : theme;
      state.theme = theme
      localStorage.setItem('theme', theme)
      document.documentElement.setAttribute('data-theme', actualTheme)
    },
    setLanguage(state, language) {
      state.language = language
      localStorage.setItem('language', language)
    }
  },
  actions: {
    initTheme({ commit }) {
      const savedTheme = localStorage.getItem('theme') || 'system'
      const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      
      const handleThemeChange = (e) => {
        if (savedTheme === 'system') {
          commit('setTheme', e.matches ? 'dark' : 'light')
        }
      }
      
      darkModeMediaQuery.addListener(handleThemeChange)
      
      if (savedTheme === 'system') {
        handleThemeChange(darkModeMediaQuery)
      } else {
        commit('setTheme', savedTheme)
      }
    }
  }
}) 